<?php

namespace app\api\service;

use app\api\model\Setmeal as SetmealModel;
use app\api\model\Dish as DishModel;
use app\api\model\ShoppingCart as ShoppingCartModel;
use app\common\exception\BusinessException;

/**
 * 购物车服务
 */
class ShoppingCart
{
    /**
     * 查看购物车
     * 
     * @param int $userId
     */
    public function showShoppingCart($userId)
    {
        $result = [];
        $list = ShoppingCartModel::all(function ($query) use ($userId) {
            $query->where('user_id', $userId)->order('create_time', 'desc');
        });
        if ($list) {
            foreach ($list as $key => $shoppingCart) {
                $result[] = [
                    'amount' => $shoppingCart->amount,
                    'createTime' => $shoppingCart->create_time,
                    'dishFlavor' => $shoppingCart->dish_flavor,
                    'dishId' => $shoppingCart->dish_id,
                    'id' => $shoppingCart->id,
                    'image' => $shoppingCart->image,
                    'name' => $shoppingCart->name,
                    'number' => $shoppingCart->number,
                    'setmealId' => $shoppingCart->setmeal_id,
                    'userId' => $shoppingCart->user_id,
                ];
            }
        }
        return $result;
    }

    /**
     * 清空购物车
     *
     * @param int $userId
     */
    public function cleanShoppingCart($userId)
    {
        $count = ShoppingCartModel::where('user_id', $userId)->count();
        if ($count == 0) {
            throw new BusinessException("购物车中没有商品");
        }
        $res = ShoppingCartModel::destroy(['user_id' => $userId]);
        if ($res === 0) {
            throw new BusinessException("清空购车失败");
        }
    }

    /**
     * 添加购物车
     *
     * @param array $data
     */
    public function addShoppingCart($data)
    {
        // 业务规则1：菜品和套餐不能同时存在
        if (isset($data['dishId']) && isset($data['setmealId'])) {
            throw new BusinessException('菜品和套餐不能同时添加');
        }

        // 构建查询条件
        $where = ['user_id' => $data['userId']];
        if (isset($data['dishFlavor'])) $where['dish_flavor'] = $data['dishFlavor'];
        if (isset($data['dishId'])) $where['dish_id'] = $data['dishId'];
        if (isset($data['setmealId'])) $where['setmeal_id'] = $data['setmealId'];

        // 查询是否已存在相同购物车项
        $existing = ShoppingCartModel::get($where);

        // 业务规则2：菜品/套餐必须存在（以dishId为例）
        if (isset($data['dishId'])) {
            $dish = DishModel::get($data['dishId']);
            if (!$dish) {
                throw new BusinessException('菜品不存在');
            }
        } elseif (isset($data['setmealId'])) {
            $setmeal = SetmealModel::get($data['setmealId']);
            if (!$setmeal) {
                throw new BusinessException('套餐不存在');
            }
        }
        if ($existing) {
            // 如果已经存在，就更新数量加1
            $existing->number += 1;
            if (!$existing->save()) {
                throw new BusinessException('跟新商品数量失败'); // 数据库保存失败
            };
        } else {
            $shoppingCart = new ShoppingCartModel;
            $shoppingCart->user_id = $data['userId'];
            // 如果不存在，插入数据，数量就是1
            $dishId = $data['dishId'] ?? null;
            if ($dishId !== null) {
                // 添加到购物车的是菜品
                $dish = DishModel::getById($dishId);
                $shoppingCart->name = $dish->name;
                $shoppingCart->dish_id = $dish->id;
                $shoppingCart->image = $dish->image;
                $shoppingCart->amount = $dish->price;
            } else {
                //添加到购物车的是套餐
                $setmeal =  SetmealModel::getById($data['setmealId']);
                $shoppingCart->name = $setmeal->name;
                $shoppingCart->setmeal_id = $setmeal->id;
                $shoppingCart->image = $setmeal->image;
                $shoppingCart->amount = $setmeal->price;
            }
            $shoppingCart->number = 1;
            if (!$shoppingCart->save()) {
                throw new BusinessException('添加购物车失败'); // 数据库保存失败
            }
        }
    }

    /**
     * 删除购物车中一个商品
     *
     * @param array $data
     */
    public function subShoppingCart($data)
    {
        // 业务规则1：菜品和套餐不能同时存在
        if (isset($data['dishId']) && isset($data['setmealId'])) {
            throw new BusinessException('菜品和套餐不能同时添加');
        }

        // 业务规则2：菜品或套餐是否存在
        if (isset($data['dishId'])) {
            $dish = DishModel::get($data['dishId']);
            if (!$dish) {
                throw new BusinessException("菜品不存在");
            }
        } elseif (isset($data['setmealId'])) {
            $setmeal = SetmealModel::get($data['setmealId']);
            if (!$setmeal) {
                throw new BusinessException("套餐不存在");
            }
        }

        // 构建查询条件
        $where = ['user_id' => $data['userId']];
        if (isset($data['dishFlavor'])) $where['dish_flavor'] = $data['dishFlavor'];
        if (isset($data['dishId'])) $where['dish_id'] = $data['dishId'];
        if (isset($data['setmealId'])) $where['setmeal_id'] = $data['setmealId'];

        // 查询是否已存在相同购物车项
        $existing = ShoppingCartModel::get($where);

        if ($existing) {
            if ($existing->number == 1) {
                if (!$existing->delete()) {
                    throw new BusinessException('删除购物车商品失败');
                };
            } else {
                $existing->number -= 1;
                if (!$existing->save()) {
                    throw new BusinessException('减去购物车商品失败');
                };
            }
        }
    }
}
